package com.crm.customers.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crm.customers.dao.CommissionCustomerDao;
import com.crm.customers.dao.CommissionDao;
import com.crm.customers.model.Commission;
import com.crm.customers.model.CommissionCustomer;
import com.crm.customers.service.ApproveItemService;
import com.crm.customers.service.CommissionService;
import com.crm.sys.dao.ApproveConfigureDao;
import com.crm.sys.model.ApproveConfigure;
import com.crm.util.Constants;

@Service("commissionService")
public class CommissionServiceImpl implements CommissionService {
	
	@Autowired
	private CommissionDao commissionDao;
	@Autowired
	private ApproveConfigureDao approveConfigureDao;
	@Autowired
	private ApproveItemService approveItemService;
	@Autowired
	private CommissionCustomerDao commissionCustomerDao;

	@Override
	public Commission saveCommission(Commission c) throws Exception  {
		//在这里要处理一下代办因为涉及到了审批 要判断存的是什么内容
		//判断是草稿还是审批
		if (c.getState() == 1) {
			//是审批,添加审批
			//设置为审批中
			c.setApprovestate(Constants.ApproveState.ONE);
			c = commissionDao.saveCommission(c);
			if (c.getId() != null && c.getId() > 0) {
				//先是获取审批流程
				String approveCode  = Constants.ApproveCode.COMMISSION;
				ApproveConfigure  cig = approveConfigureDao.selectByPrimaryKey(approveCode); 
				//插入到审批表
				approveItemService.saveApprove(cig, c.getId(), c.getId(), c.getCreateuser(), c.getCreateuserName());
			}
		} else {
			c = commissionDao.saveCommission(c);
		}
		return c;
	}

	@Override
	public Commission getcommissionInfoById(Commission c) {
		c = commissionDao.getcommissionInfoById(c);
		return c;
	}

	@Override
	public int updateCommissionApprovestate(Commission c) {
		return commissionDao.updateCommissionApprovestate(c);
	}

	@Override
	public int approveCommission(Commission c) throws Exception   {
		int result = 0;
		if (c.getId() != null) {
			//先是获取审批流程
			String approveCode  = Constants.ApproveCode.COMMISSION;
			ApproveConfigure  cig = approveConfigureDao.selectByPrimaryKey(approveCode); 
			//插入到审批表
			approveItemService.saveApprove(cig, c.getId(), c.getId(), c.getCreateuser(), c.getCreateuserName());
			//更新代办状态为已申请审批
			c.setState(1);
			commissionDao.updateCommission(c);
			result = 1;
		}
		return result;
	}

	@Override
	public String getOverruleReason(Commission c) {
		return commissionDao.getOverruleReason(c);
	}

	@Override
	public Integer getCommMoneyByCreatedate(Commission c) {
		Integer result = commissionDao.getCommMoneyByCreatedate(c);
		if (result == null) {
			result = 0;
		} 
		return result;
	}
	
}
